package com.crawler.waf.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSONObject;
import com.crawler.waf.exceptions.extendExceptions.WafSimpleException;

public class ExceptionFilter extends OncePerRequestFilter {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		try {
			filterChain.doFilter(request, response);
		} catch (Exception ex) {
			if (ex instanceof AuthenticationException) {
				ex = new WafSimpleException(HttpStatus.FORBIDDEN, "WAF/ACCESS_DENIED", "授权过程发生异常");
			} else if (ex instanceof SQLException) {
				ex = new WafSimpleException("数据库操作异常");
			}
			String inputLine;
			String bodyStr = "";
			try {
				BufferedReader br = request.getReader();
				while ((inputLine = br.readLine()) != null) {
					bodyStr += inputLine;
				}
				br.close();
			} catch (IOException e) {
			}

			if(!"OPTIONS".equalsIgnoreCase(request.getMethod())){
				JSONObject error = new JSONObject();
				
				error.put("requestURL", request.getRequestURL());
				error.put("method", request.getMethod());
				error.put("authorization", request.getHeader("Authorization"));
				error.put("queryString ", request.getQueryString());
				error.put("body", bodyStr);
				LOGGER.error("=============异常输出===============");
				LOGGER.error(error.toString());
				LOGGER.error(ex.getMessage());
			}
			
			request.setAttribute("exception", ex);
			request.getRequestDispatcher("/exception").forward(request, response);
		}
	}
}
